package main

import (
	"encoding/csv"
	"fmt"
	"os"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/axgle/mahonia"
	"github.com/boombuler/barcode/code128"
	"github.com/jung-kurt/gofpdf"
	"github.com/jung-kurt/gofpdf/contrib/barcode"
)

func main() {
	var path string
	fmt.Println("请输入CSV文件路径（或者拖入文件）直接回车默认使用程序同文件夹下的“箱样例.csv”文件：")
	fmt.Scanln(&path)
	if path == "" {
		dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
		if err != nil {
			fmt.Println("路径错误")
		}
		path = filepath.Join(dir, "箱样例.csv")
	}

	file, err := os.Open(path)
	paths := filepath.Dir(path)
	if err != nil {
		fmt.Println(err)
	}
	defer file.Close()
	decoder := mahonia.NewDecoder("GBK")
	csvreder := csv.NewReader(decoder.NewReader(file))

	ss, _ := csvreder.ReadAll()

	// fmt.Println(ss)
	// fmt.Println(paths)
	// 行
	rows := len(ss)
	// 列
	columns := len(ss[0])

	for column := 0; column < columns; column++ {

		outpath := filepath.Join(paths, "箱"+strconv.Itoa(column+1)+".pdf")
		// fmt.Println(outpath)
		//创建pdf
		pdf := gofpdf.New("L", "mm", "A4", "")

		// pdf := gofpdf.New("P", "mm", 267, 200)
		pdf.AddUTF8Font("宋体", "R", "Font/simsun.ttf")
		pdf.AddUTF8Font("黑体", "L", "Font/msyhl.ttf")
		pdf.AddUTF8Font("黑体", "R", "Font/msyhR.ttf")

		for row := 1; row < rows; row++ {
			names := strings.Split(ss[row][column], "----")

			// fmt.Println(names)
			if err != nil {
				fmt.Println(err)
				continue
			}
			// fmt.Println(names)
			name := names[0]
			code := names[1]
			loop, err := strconv.Atoi(names[2])
			if err != nil {
				fmt.Println(err)
			}
			for i := 0; i < loop; i++ {

				pdf.AddPage()
				// 创建条形码
				bcode, err := code128.Encode(names[1])

				if err == nil {
					key := barcode.Register(bcode)
					var width float64 = 254.5
					var height float64 = 77.6
					barcode.BarcodeUnscalable(pdf, key, 21, 11.5, &width, &height, false)
					// err = pdf.OutputFileAndClose("barcode.pdf")
				}

				//创建文本
				pdf.SetFont("宋体", "R", 84)
				pdf.SetLeftMargin(11.5)
				pdf.SetRightMargin(11.5)
				pdf.SetY(111)
				pdf.CellFormat(0, 0, code, "0", 0, "C", false, 0, "")

				pdf.SetFont("黑体", "L", 60)
				pdf.SetWordSpacing(30)
				pdf.SetLeftMargin(11.5)
				pdf.SetRightMargin(11.5)
				pdf.SetY(148)
				pdf.CellFormat(0, 0, name, "0", 0, "C", false, 0, "")

				pdf.SetFont("黑体", "R", 58)
				pdf.SetLeftMargin(11.5)
				pdf.SetRightMargin(11.5)
				pdf.SetY(186)
				pdf.CellFormat(0, 0, "Made in China", "0", 0, "C", false, 0, "")
			}
		}

		if err := pdf.OutputFileAndClose(outpath); err != nil {
			panic(err.Error())
		}

	}
	fmt.Println("输入任意字符退出！")
	fmt.Scanln()
}
